package shader;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

import javax.media.opengl.GL;


public class WaveShader {
//	final static String f_file = "src/shader/depth_fshader.txt";
//	final static String v_file = "src/shader/depth_vshader.txt";
//	final static String f_file = "src/shader/toon_fshader.txt";
//	final static String v_file = "src/shader/toon_vshader.txt";

	final static String f_file = "";
	final static String v_file = "src/shader/vshader.txt";
	
	static int fid = -1;
	static int vid = -1;
	private static int programID;
	static int wave = -1;
	
	public static void init(GL gl) throws IOException{

		if (f_file != null && f_file.length() > 0){
			String fcode = read(f_file);
			fid = gl.glCreateShader(GL.GL_FRAGMENT_SHADER);
			compile(gl, fid, fcode);
		}

		if (v_file != null && v_file.length() > 0){
			String vcode = read(v_file);
			vid = gl.glCreateShader(GL.GL_VERTEX_SHADER);
			compile(gl, vid, vcode);
		}
		programID = link(gl, fid,vid);
		wave = gl.glGetAttribLocation(programID, "wave");

	}
	static void compile(GL gl, int id, String code){
		gl.glShaderSource(id, 1, new String[]{code}, new int[]{code.length()},0);
		gl.glCompileShader(id);
	}

	static int link(GL gl, int fid, int vid){
		int shaderprogram = gl.glCreateProgram();

		if (vid >= 0)
			gl.glAttachShader(shaderprogram, vid);
		if (fid >= 0)
			gl.glAttachShader(shaderprogram, fid);

		if (vid >= -1 || fid >= -1){
			gl.glLinkProgram(shaderprogram);
		}
		return shaderprogram;
	}
	
	public static void useShader(GL gl){
		gl.glUseProgram(programID);
	}
	
	public static void unuseShader(GL gl){
		gl.glUseProgram(0);
	}
	
	static String read(String file) throws IOException{
		BufferedReader brv = new BufferedReader(new FileReader(file));
		String vsrc = "";
		String line;
		while ((line=brv.readLine()) != null) {
			vsrc += line + "\n";
		}
		return vsrc;
	}
	
	public static int getWave(){
		return wave;
	}
	public static void setWaveStrength(GL gl,float wavestrenght) {
		gl.glVertexAttrib1f(WaveShader.getWave(), wavestrenght);
	}
}


/*
vShader=gl.glCreateShaderObjectARB(GL.GL_VERTEX_SHADER_ARB);
fShader=gl.glCreateShaderObjectARB(GL.GL_FRAGMENT_SHADER_ARB);
// attaching sources
gl.glShaderSourceARB(vShader, 1, new String[]{vShaderSrc}, new int[]{vShaderSrc.length()},0);
gl.glShaderSourceARB(fShader, 1, new String[]{fShaderSrc}, new int[]{fShaderSrc.length()},0);
// compiling
gl.glCompileShaderARB(vShader);
gl.glCompileShaderARB(fShader);
// creating program object
shaderPrg=gl.glCreateProgramObjectARB();

gl.glAttachObjectARB(shaderPrg, vShader);
gl.glAttachObjectARB(shaderPrg, fShader);

// linking and using program
gl.glLinkProgramARB(shaderPrg);
gl.glUseProgramObjectARB(shaderPrg);
 */